from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

def get_user_data():
    userid_password = {}
    userid_gender = {}
    for line in open('user.csv',encoding='utf-8'):
        line = line.strip()
        if ',' not in line:
            continue
        userid,gender = line.split(',')
        userid_gender[userid] = gender
        userid_password[userid] = userid[-4:]
    
    return userid_password,userid_gender

userid_password,userid_gender = get_user_data()

@app.get("/user/{userid}")
async def get_usergender(userid):
    '''
    根据传入的userid来返回对应的性别
    '''
    return {"username":userid,"gender":userid_gender.get(userid,'None')}

class User(BaseModel):
    userid:str
    password:str

@app.post("/login")
async def validate_user(user: User):
    '''
    发送用户的用户名及密码用于验证
    '''
    print(userid_password)
    if userid_password.get(user.userid,None) == user.password:
        return {"state":True}
    return {"state":False}

if __name__ == '__main__':
    uvicorn.run(app,host="127.0.0.1",port=8000)